package com.cyzy.controller;

import com.cyzy.entity.RequestDTO;
import com.cyzy.entity.User;
import com.cyzy.service.UserService;
import com.cyzy.service.FileUploadService;
import com.cyzy.service.CameraIntegrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人中心综合控制器
 * 整合用户信息、文件上传、摄像头功能
 */
@RestController
@RequestMapping("/api/personal-center")
@CrossOrigin(origins = "*")
public class PersonalCenterController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FileUploadService fileUploadService;
    
    @Autowired
    private CameraIntegrationService cameraIntegrationService;
    
    /**
     * 获取个人中心首页数据
     */
    @GetMapping("/dashboard/{userId}")
    public RequestDTO getDashboard(@PathVariable String userId) {
        try {
            User user = userService.findById(userId);
            Object statistics = userService.getUserStatistics(userId);
            
            // 隐藏敏感信息
            user.setPassword(null);
            
            Map<String, Object> dashboard = new HashMap<>();
            dashboard.put("userInfo", user);
            dashboard.put("statistics", statistics);
            dashboard.put("profileCompletion", calculateProfileCompletion(user));
            dashboard.put("isVerified", user.getRealNameVerified() == 1);
            dashboard.put("hasAvatar", user.getAvatar() != null && !user.getAvatar().isEmpty());
            dashboard.put("roleText", user.getRole() == 1 ? "教师" : "学生");
            
            return new RequestDTO(200, "获取个人中心数据成功", dashboard);
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 完整的实名认证流程
     */
    @PostMapping("/complete-verification")
    public RequestDTO completeVerification(@RequestParam String userId,
                                         @RequestParam String realName,
                                         @RequestParam String idCard,
                                         @RequestParam(required = false) String faceImageBase64,
                                         @RequestParam(required = false, value = "idCardFile") MultipartFile idCardFile) {
        try {
            Map<String, Object> verificationResult = new HashMap<>();
            
            // 1. 基本信息验证
            if (realName == null || realName.trim().isEmpty()) {
                return new RequestDTO(500, "真实姓名不能为空", null);
            }
            
            if (idCard == null || idCard.length() != 18) {
                return new RequestDTO(500, "身份证号格式不正确", null);
            }
            
            // 2. 上传身份证照片（如果有）
            String idCardUrl = null;
            if (idCardFile != null && !idCardFile.isEmpty()) {
                idCardUrl = fileUploadService.uploadFile(idCardFile, "id-cards", userId);
                verificationResult.put("idCardImageUrl", idCardUrl);
            }
            
            // 3. 人脸验证（如果有）
            boolean faceVerified = false;
            if (faceImageBase64 != null && !faceImageBase64.isEmpty()) {
                Map<String, Object> faceResult = cameraIntegrationService.verifyFace(userId, faceImageBase64);
                faceVerified = Boolean.TRUE.equals(faceResult.get("success"));
                verificationResult.put("faceVerificationResult", faceResult);
            }
            
            // 4. 更新实名认证信息
            boolean identityUpdated = userService.verifyIdentity(userId, realName, idCard);
            
            if (identityUpdated) {
                verificationResult.put("identityVerified", true);
                verificationResult.put("faceVerified", faceVerified);
                verificationResult.put("realName", realName);
                verificationResult.put("idCard", maskIdCard(idCard));
                
                return new RequestDTO(200, "实名认证完成", verificationResult);
            } else {
                return new RequestDTO(500, "实名认证失败", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 上传并更新头像
     */
    @PostMapping("/upload-avatar")
    public RequestDTO uploadAndUpdateAvatar(@RequestParam("file") MultipartFile file,
                                          @RequestParam String userId) {
        try {
            // 上传头像到对象存储
            String avatarUrl = fileUploadService.uploadAvatar(file, userId);
            
            // 更新用户头像
            boolean updated = userService.updateAvatar(userId, avatarUrl);
            
            if (updated) {
                Map<String, Object> result = new HashMap<>();
                result.put("avatarUrl", avatarUrl);
                result.put("userId", userId);
                result.put("uploadTime", System.currentTimeMillis());
                
                return new RequestDTO(200, "头像上传成功", result);
            } else {
                return new RequestDTO(500, "头像更新失败", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 获取个人设置
     */
    @GetMapping("/settings/{userId}")
    public RequestDTO getPersonalSettings(@PathVariable String userId) {
        try {
            User user = userService.findById(userId);
            
            Map<String, Object> settings = new HashMap<>();
            settings.put("userId", user.getId());
            settings.put("username", user.getUsername());
            settings.put("nickname", user.getNickname());
            settings.put("phone", user.getPhone());
            settings.put("avatar", user.getAvatar());
            settings.put("gender", user.getGender());
            settings.put("age", user.getAge());
            settings.put("realName", user.getRealName());
            settings.put("realNameVerified", user.getRealNameVerified() == 1);
            settings.put("role", user.getRole());
            settings.put("roleText", user.getRole() == 1 ? "教师" : "学生");
            settings.put("profileCompletion", calculateProfileCompletion(user));
            settings.put("createTime", user.getCreateTime());
            settings.put("updateTime", user.getUpdateTime());
            
            return new RequestDTO(200, "获取个人设置成功", settings);
        } catch (Exception e) {
            return new RequestDTO(500, e.getMessage(), null);
        }
    }
    
    /**
     * 计算个人资料完成度
     */
    private int calculateProfileCompletion(User user) {
        int completion = 0;
        int totalFields = 8;
        
        if (user.getNickname() != null && !user.getNickname().isEmpty()) completion++;
        if (user.getPhone() != null && !user.getPhone().isEmpty()) completion++;
        if (user.getAvatar() != null && !user.getAvatar().isEmpty()) completion++;
        if (user.getGender() != null) completion++;
        if (user.getAge() != null) completion++;
        if (user.getRealName() != null && !user.getRealName().isEmpty()) completion++;
        if (user.getIdCard() != null && !user.getIdCard().isEmpty()) completion++;
        if (user.getRealNameVerified() == 1) completion++;
        
        return (completion * 100) / totalFields;
    }
    
    /**
     * 脱敏身份证号
     */
    private String maskIdCard(String idCard) {
        if (idCard == null || idCard.length() < 8) {
            return idCard;
        }
        return idCard.substring(0, 4) + "**********" + idCard.substring(idCard.length() - 4);
    }
}
